package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.vo.GetRoomsWithDeviceByFloorIdVO;
import com.zzyl.nursing.vo.RoomVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private RedisTemplate<String, String> redis;

    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    /**
     * 根据房间ID查询房间数据
     *
     * @param id 房间ID
     * @return 查到的结果
     */
    @Override
    public RoomVo getRoomVoByRoomId(Integer id) {
        return roomMapper.getRoomVoByRoomId(id);
    }

    @Override
    public List<GetRoomsWithDeviceByFloorIdVO> getRoomsWithDeviceByFloorId(Long floorId) {
        List< GetRoomsWithDeviceByFloorIdVO> voList = roomMapper.selectRoomsWithDeviceByFloorId(floorId);

        List<GetRoomsWithDeviceByFloorIdVO> dataVos = new ArrayList<>();
        for (GetRoomsWithDeviceByFloorIdVO vo : voList) {
            GetRoomsWithDeviceByFloorIdVO vo1 = abc(vo);
            dataVos.add(vo1);
        }
        return  dataVos;
    }

    private GetRoomsWithDeviceByFloorIdVO abc(GetRoomsWithDeviceByFloorIdVO vo) {
        // 取出房间设备集合
        List<GetRoomsWithDeviceByFloorIdVO.DeviceVO> roomDeviceList = vo.getDeviceVos();
        // 判断房间是否存在设备
        if (CollectionUtil.isNotEmpty(roomDeviceList)) {
            // 取出房间中设备id
            List<GetRoomsWithDeviceByFloorIdVO.DeviceVO> collect = roomDeviceList.stream().peek(
                    (roomDevice) -> {
                        String roomIotId = roomDevice.getIotId();
                        try {
                            Object jsonObj = redis.opsForHash().get(CacheConstants.IOT_DEVICEDATA_LATEST, roomIotId);
                            if (!Objects.isNull(jsonObj)) {
                                List<GetRoomsWithDeviceByFloorIdVO.DeviceDataVO> list = JSONUtil.toList(jsonObj.toString(), GetRoomsWithDeviceByFloorIdVO.DeviceDataVO.class);
                                list = list.stream().map((deviceDataVO) -> {
                                    deviceDataVO.setDataValue(JSONUtil.toBean(deviceDataVO.getDataValue(), Map.class).get("value").toString());
                                    return deviceDataVO;
                                }).collect(Collectors.toList());

                                roomDevice.setDeviceDataVos(list);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
            ).collect(Collectors.toList());
            vo.setDeviceVos(collect);
        }
        // 处理床位的设备数据
        List<GetRoomsWithDeviceByFloorIdVO.BedVO> bedVolist = vo.getBedVoList();
        if (CollectionUtil.isNotEmpty(bedVolist)) {

            List<GetRoomsWithDeviceByFloorIdVO.BedVO> collect = bedVolist.stream().map((bedVO) -> {

                // 获取床位的设备信息
                List<GetRoomsWithDeviceByFloorIdVO.DeviceVO> deviceVos = bedVO.getDeviceVos();

                // 给设备封装设备数据
                List<GetRoomsWithDeviceByFloorIdVO.DeviceVO> deviceVOList = deviceVos.stream().map((deviceVO) -> {
                    String iotId = deviceVO.getIotId();
                    try {
                        Object jsonObj = redis.opsForHash().get(CacheConstants.IOT_DEVICEDATA_LATEST, iotId);
                        if (!Objects.isNull(jsonObj)) {
                            List<GetRoomsWithDeviceByFloorIdVO.DeviceDataVO> list = JSONUtil.toList(jsonObj.toString(), GetRoomsWithDeviceByFloorIdVO.DeviceDataVO.class);
                            list = list.stream().map((deviceDataVO) -> {
                                deviceDataVO.setDataValue(JSONUtil.toBean(deviceDataVO.getDataValue(), Map.class).get("value").toString());
                                return deviceDataVO;
                            }).collect(Collectors.toList());
                            deviceVO.setDeviceDataVos(list);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return deviceVO;
                }).collect(Collectors.toList());
                // 将设备信息和设备的数据设备到床位VO
                bedVO.setDeviceVos(deviceVOList);
                return bedVO;
            }).collect(Collectors.toList());
            vo.setBedVoList(collect);
        }
        return vo;
    }

    /**
     * 查询指定楼层下的所有有智能设备的房间数据和床位数据
     *
     * @param floorId 楼层id
     * @return 数据
     */
//    @Override
//    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
//        List<RoomVo> roomVos = roomMapper.getRoomsWithDeviceByFloorId(floorId);
//        // 补全设备运行数据，从redis中获取
//        // 从roomVos中取出所有房间中的设备集合
//        roomVos.forEach(roomVo -> {
//            // 取出房间内的设备集合
//            roomVo.getDeviceVos().forEach(deviceVo -> {
//                // deviceVo：房间内的一个设备
//                // 取出这个设备的运行数据
//                String jsonStr = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICEDATA_LATEST, deviceVo.getIotId());
//                if (StringUtils.isEmpty(jsonStr)) {
//                    return;
//                }
//                deviceVo.setDeviceDataVos(JSONUtil.toList(jsonStr, DeviceData.class));
//            });
//
//            // 补全床位上的所有设备的数据
//            roomVo.getBedVoList().forEach(bedVo -> {
//                // 遍历房间内的床位的集合，bedVo代表拿到的一个床位
//                bedVo.getDeviceVos().forEach(deviceVo -> {
//                    // deviceVo：床位内的一个设备
//                    // 取出这个设备的运行数据
//                    String jsonStr = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICEDATA_LATEST, deviceVo.getIotId());
//                    if (StringUtils.isEmpty(jsonStr)) {
//                        return;
//                    }
//                    deviceVo.setDeviceDataVos(JSONUtil.toList(jsonStr, DeviceData.class));
//                });
//            });
//        });
//        return roomVos;
//    }
}
